package com.gitee.urick.union.api.union.action;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.gitee.urick.union.api.union.IHandler;
import com.gitee.urick.union.api.union.dto.ReqCtx;
import com.gitee.urick.union.api.union.dto.base.BaseRes;
import io.micrometer.core.instrument.util.IOUtils;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * 修改记录
 * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 * 修改日期				修改者						备注信息
 * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 * 2020年09月27日			kkroc							初始化版本
 */
@Slf4j
@Controller
public class UnionV2Action {
    @Autowired
    @Qualifier("dispatcher_v2")
    private IHandler dispatcher;

    @RequestMapping(value = "/api/v2/{action}",
            consumes = {MediaType.APPLICATION_JSON_VALUE},
            produces = {MediaType.APPLICATION_JSON_VALUE},
            method = {RequestMethod.POST}
    )
    protected void dispatch(@PathVariable String action, @RequestBody String params, HttpServletRequest request, HttpServletResponse response) throws IOException, Exception {
        try (PrintWriter out = response.getWriter()) {
            log.info("Input Api Request: {} And Params: {}", action, params);
            String data = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
            ReqCtx ctx = ReqCtx.newCtx(action, data, request.getHeader("sign"));
            dispatcher.handle(ctx);

            BaseRes res = ctx.getRes();
            if (StrUtil.isBlank(res.getStatus())) {
                if (ctx.isTerminated()) res.error();
                else res.success();
            }
            // Generate sign str
            String resp = JSON.toJSONString(res);
            log.info("Output Api Request: {} And Params: {}", action, resp);
            out.print(resp);
            out.flush();
        }
    }
}
